#pragma once

#include<vector>
#include<iostream>
using namespace std;

enum State
{
	EMPTY,
	EXIST,
	DELETE
};

// Note: assumes long is at least 32 bits.
static const int __stl_num_primes = 28;
static const unsigned long __stl_prime_list[__stl_num_primes] = {
53,         97,         193,       389,       769,
1543,       3079,       6151,      12289,     24593,
49157,      98317,      196613,    393241,    786433,
1572869,    3145739,    6291469,   12582917,  25165843,
50331653,   100663319,  201326611, 402653189, 805306457,
1610612741, 3221225473, 4294967291
};

inline unsigned long __stl_next_prime(unsigned long n)
{
	const unsigned long* first = __stl_prime_list;
	const unsigned long* last = __stl_prime_list + __stl_num_primes;
	const unsigned long* pos = lower_bound(first, last, n);
	return pos == last ? *(last - 1) : *pos;
}

template<class K, class V>
struct HashData
{
	pair<K, V> _data;
	State _state;
	HashData(const pair<K, V>& kv = pair<K, V>(), State s = EMPTY)
		:_data(kv), _state(s)
	{
	}
};

template<class K>
struct HashFunc
{
	size_t operator()(const K& k)
	{
		return (size_t)k;
	}
};

template<>
struct HashFunc<string>
{
	size_t operator()(const string& k)
	{
		size_t hash = 0;
		for (auto c : k)
		{
			hash += c;
			hash *= 131;
		}
		return hash;
	}
};

template<class K, class V, class Hash = HashFunc<K>>
class Hash_Tab
{
public:

	Hash_Tab(size_t n = 1)
		:_tab(__stl_next_prime(n)), _n(0)
	{
	}

	bool Insert(const pair<K, V>& kv)
	{
		if (Find(kv.first))
			return false;

		HashData<K, V> data(kv, EXIST);
		Hash hs;

		if ((double)_n / (double)_tab.size() >= 0.7)
		{
			Hash_Tab<K, V> newHT(_tab.size() + 1);
			for (int i = 0; i < _tab.size(); i++)
			{
				if (_tab[i]._state == EXIST)
					newHT.Insert(_tab[i]._data);
			}
			newHT.Insert(kv);
			_tab.swap(newHT._tab);
			++_n;
			return true;
		}

		size_t hash0 = hs(kv.first) % _tab.size();
		size_t i = 1;
		size_t hashi = hash0;

		while (_tab[hashi]._state == EXIST)
		{
			hashi = (hashi + i) % _tab.size();
			++i;
		}
		_tab[hashi] = data;
		++_n;

		return true;
	}

	HashData<K, V>* Find(const K& key)
	{
		Hash hs;
		size_t hash0 = hs(key) % _tab.size();
		size_t i = 1;
		size_t hashi = hash0;

		while (_tab[hashi]._state != EMPTY)
		{
			if (_tab[hashi]._data.first == key && _tab[hashi]._state == EXIST)
				return &(_tab[hashi]);

			hashi = (hashi + i) % _tab.size();
			++i;
		}

		return nullptr;
	}

	bool Erase(const K& k)
	{
		HashData<K, V>* pos = Find(k);
		if (pos)
		{
			pos->_state = DELETE;
			return true;
		}
		return false;
	}

private:
	vector<HashData<K, V>> _tab;
	size_t _n;
};